import * as XLSX from 'xlsx';
import Encoding from 'encoding-japanese';

/**
 * 根据列序号生成Excel风格的列名（A, B, ..., Z, AA, AB, ...）
 * @param n 列序号（从0开始）
 * @returns Excel列名
 */
function getExcelColName(n: number): string {
  let s = '';
  while (n >= 0) {
    s = String.fromCharCode((n % 26) + 65) + s;
    n = Math.floor(n / 26) - 1;
  }
  return s;
}

/**
 * 解析Excel或CSV文件，返回二维数组数据
 * @param file 选中的文件对象
 * @param skipRows 跳过的行数（如skip 1表示跳过首行）
 * @returns Promise<二维数组>，每个子数组为一行
 */
export async function parseFile(file: File, skipRows = 0): Promise<any[][]> {
  const fileExt = file.name.toLowerCase().split('.').pop();
  if (!fileExt || !['xlsx', 'csv'].includes(fileExt)) {
    throw new Error('只支持Excel或CSV文件');
  }
  let workbook;
  if (fileExt === 'csv') {
    // 读取CSV文件，自动判断编码
    const arrayBuffer = await file.arrayBuffer();
    const data = new Uint8Array(arrayBuffer);
    let text = '';
    if (Encoding.detect(data) === 'UTF8') {
      text = new TextDecoder('utf-8').decode(data);
    } else {
      const unicodeArr = Encoding.convert(data, { to: 'UNICODE', from: 'AUTO' });
      text = Encoding.codeToString(unicodeArr);
    }
    workbook = XLSX.read(text, { type: 'string' });
  } else {
    // 读取Excel文件
    const arrayBuffer = await file.arrayBuffer();
    const data = new Uint8Array(arrayBuffer);
    workbook = XLSX.read(data, { type: 'array' });
  }
  const firstSheetName = workbook.SheetNames[0];
  const worksheet = workbook.Sheets[firstSheetName];
  // 跳过skipRows行，返回二维数组
  const json = XLSX.utils.sheet_to_json(worksheet, { header: 1, range: skipRows });
  return json as any[][];
}

/**
 * 渲染二维数组为带Excel风格表头的HTML表格
 * @param json 二维数组数据
 * @returns HTML字符串
 */
export function renderTable(json: any[][]): string {
  if (!json.length) return '';
  // 计算最大列数，保证所有行对齐
  const colCount = Math.max(...json.map(row => row.length));
  // 生成表头
  let html = '<table border="1" style="border-collapse:collapse;">';
  html += '<thead><tr>';
  for (let i = 0; i < colCount; ++i) {
    html += `<th>${getExcelColName(i)}</th>`;
  }
  html += '</tr></thead><tbody>';
  // 渲染数据区，每行不足的列补空
  json.forEach(row => {
    html += '<tr>' + Array.from({length: colCount}).map((_, i) => `<td>${row[i] ?? ''}</td>`).join('') + '</tr>';
  });
  html += '</tbody></table>';
  return html;
} 